/**
 * Created by MAJIANGTAO on 2015/12/9.
 */

define('upload',['session'], function (session) {
    var token = '';
    var config = {
        defaultHtml : '',
        token : '',
        id:'',
        projectId : '',
        url : '',
        method : 'post',
        isOnly : false,
        isFujian : false,
        isMobile : false,
        isPaste : false,
        channel : false,
        imageIds : {
            array : [],
            setId : function (arr) {
                this.array = arr;
            },
            getId : function () {
                return this.array;
            }
        },
        attachmentIds : {
            array : [],
            setId : function (arr) {
                this.array = arr;
            },
            getId : function () {
                return this.array;
            }
        },
        getDefaultHtml : function(){
            return this.defaultHtml;
        },
        getIsOnly : function () {
            return this.isOnly;
        }
    };
    $.fn.listen = function (type, fn) {
        return this.each(function () {
            $(this)[0].addEventListener(type, function (e) {
                if(!fn.call($(this),e)){
                    e.stopPropagation();
                    e.preventDefault();
                }
            });
        })
    };

    var file_input, file_form;
    var flag = true,f_flag = true;

    $.fn.uploadImageInit = function () {
        //console.log($(this).attr('data-config'));
        var c = JSON.parse($(this).attr('data-config'));
        init($(this),c);
        if(c.isFujian){
            f_flag = true;
            config.attachmentIds.setId([]);
        }else{
            flag = true;
            config.imageIds.setId([]);
        }
    };

    $.fn.uploadImage = function (json,fn) {
        if(json.token != ''){
            token = json.token;
        }else{
            token = bugCloseStorage.getItem('token');
        }
        var $this = $(this);
        config.defaultHtml = $this.html();
        config = $.extend({},config,json);
        $this.config = config;
        $this.attr('data-config',JSON.stringify(config))
        //console.log($this)
        $this.bind('dragenter', function () {
            return false;
        }).bind('dragover', function () {
            return false;
        }).listen('drop', function (e) {
            var files = e.dataTransfer;
            config = $this.config;
            uploadImg($this,files,fn);
        }).bind('paste', function (e) {
            //console.log('粘贴图片',$this.config);
            config = $this.config;
            if(config.isPaste){
                var items = (e.clipboardData  || e.originalEvent.clipboardData).items;
                var file ;
                var file_flag = true;
                for (var i = 0; i < items.length; i++){
                    if (items[i].type.indexOf("image") === 0 && items[i].kind === 'file'){
                        file_flag = false;
                        file = items[i].getAsFile();
                        //console.log(file);
                        if(config.isFujian){
                            if(f_flag && config.attachmentIds.getId().length == 0){
                                $this.empty();
                                f_flag = false;
                            }
                        }else{
                            if(flag && config.imageIds.getId().length == 0){
                                $this.empty();
                                flag = false;
                                $this.addClass('upload-file-bg');
                            }
                        }
                        var img_type = file.type;
                        var img_size = file.size;
                        if(img_type == 'image/jpeg' || img_type == 'image/png' || img_type == 'image/bmp' || img_type =='image/gif' || img_type == 'image/jpg'){
                            if(img_size <= 1024*1024*6 && img_size > 0){
                                var random = '';
                                for(var n=0;n<10;n++){
                                    random += Math.floor(Math.random()*10);
                                }
                                var reader = new FileReader();
                                reader.onload = function(evt){
                                    if($this.children().length >= GLOBAL.ImageNumber){
                                        layer.msg('最多上传'+GLOBAL.ImageNumber+'张图片');
                                        return false;
                                    }
                                    $this.removeClass('upload-file-bg');
                                    if(config.getIsOnly()){
                                        $this.html("<div class='upload-img' id='img-"+random+"'>" +
                                            "<div class='ui-image'><img src='"+ evt.target.result +"'  /></div>" +
                                            "<div class='ui-progress'></div>" +
                                            "</div> ");
                                    }else{
                                        $this.append("<div class='upload-img' id='img-"+random+"'>" +
                                            "<div class='ui-image'><img src='"+ evt.target.result +"'  /></div>" +
                                            "<div class='ui-progress'></div>" +
                                            "</div> ");
                                        if(typeof config.draggable != 'undefined'){
                                            if(config.draggable){
                                                $this.gridly();
                                            }
                                        }else{
                                            $this.gridly();
                                        }
                                    }

                                    var formData = new FormData();
                                    formData.append('token',bugCloseStorage.getItem('token'));
                                    if(config.isMobile)
                                        formData.append('projectId',config.projectId);
                                    else
                                        formData.append('projectId',_projectId);
                                    formData.append('channel',config.channel);
                                    formData.append('file',file);
                                    formData.append('id',config.id);
                                    ajax(formData, function (percent) {
                                        if(percent == 100){
                                            $('#img-'+random+' .ui-progress').html('正在处理');
                                        }else{
                                            $('#img-'+random+' .ui-progress').html(percent+'%');
                                        }
                                    }, function (rs) {
                                        console.log('上传结果',rs);
                                        if(rs.success){
                                            $('#img-'+random+' .ui-progress').html('上传完成');
                                            $('#img-'+random+' .ui-image img').attr({'src':rs.root.thumbUrl,'layer-src':rs.root.url,'alt':rs.root.originalFileName,'title':rs.root.originalFileName});
                                            $('#img-'+random+' .ui-progress').remove();
                                            if(config.getIsOnly()){
                                                return false;
                                            }
                                            $this.find('#img-'+random).append("<div class='ui-opts' data-action='del' id='"+rs.root.id+"'><i class='fa fa-times-circle-o' alt='删除' title='删除'></i></div><div class='ui-opts ui-opts-edit' data-action='edit' data-name='"+rs.root.originalFileName+"' id='"+rs.root.id+"'><i class='fa fa-pencil-square-o' alt='编辑名称' title='编辑名称'></i></div>");
                                            config.imageIds.getId().push(rs.root.id);
                                            bindOptions($this, function () {

                                            });
                                        }else{
                                            $('#img-'+random+' .ui-progress').html('上传失败').addClass('ui-fail').removeClass('ui-progress');
                                            $this.find('#img-'+random).append("<div class='ui-opts' data-action='del'><i class='fa fa-times-circle-o' alt='删除' title='删除'></i></div>");
                                            bindOptions($this,function(){});
                                        }
                                    });
                                    $('#img-'+random+' .upload-img').click(function(e){
                                        return false;
                                    });
                                };
                                reader.readAsDataURL(file);
                            }else if(img_size > 1024*1024*6){
                                layer.msg('图片太大，不能超过6M');
                            }else{
                                layer.msg('无效的图片');
                            }
                        }else{
                            console.log('无效格式');
                        }
                    }
                }
                if(file_flag){
                    layer.msg('该粘贴内容非图片格式');
                }
            }
        });
        if($this.config.getIsOnly()){
            $this.click(function () {
                selectImage();
            });
        }else{
            $this.siblings('.selectImages').click(function () {
                selectImage();
            });
        }
        var selectImage = function () {
            config = $this.config;
            console.log(config);
            window.fileChange = function (th) {
                uploadImg($this,th,fn);
            };
            // if(config.isMobile){
            //     window.fileChange = function (th) {
            //         uploadImg($this,th,fn);
            //     };
            // }else{
            //     window.fileChange = function (th) {
            //         if (!!window.ActiveXObject || "ActiveXObject" in window){
            //             uploadImg($this,th,fn);
            //         }
            //     };
            // }
            file_form = $('<form enctype="multipart/form-data" accept-charset="UTF-8"></form>');
            if(config.getIsOnly()){
                file_input = $('<input type="file" name="file" onchange="fileChange(this)" accept="image/*" >');
            }else{
                if(config.isFujian){
                    file_input = $('<input type="file" name="file" onchange="fileChange(this)" multiple="multiple">');
                }else{
                    file_input = $('<input type="file" name="file" accept="image/jpeg,image/png,image/bmp,image/gif,image/jpg" onchange="fileChange(this)" multiple="multiple">');
                }
            }
            file_input.appendTo(file_form);
            file_input.click();
            // file_input.change(function (file) {
            //     //uploadImg($this,file.target,fn);
            //     if(!config.isMobile)
            //         uploadImg($this,file.target,fn);
            // });

        };

    };

    function init(th,config){
        //console.log(th);
        if(config.isFujian){
            f_flag = true;
        }else{
            flag = true;
            if(!config.isOnly)
                th.addClass('upload-file-bg');
        }
        th.html(config.defaultHtml);
    }

    function uploadImg(th,file,callback){
        //console.log(config);
        if(config.token != ''){
            token = config.token;
        }else{
            token = bugCloseStorage.getItem('token');
        }
        var files = file.files;
        if(files.length){
            if(!config.getIsOnly()){
                if(config.isFujian){
                    if(f_flag && config.attachmentIds.getId().length == 0){
                        th.empty();
                        f_flag = false;
                    }
                }else{
                    if(flag && config.imageIds.getId().length == 0){
                        th.empty();
                        flag = false;
                        th.addClass('upload-file-bg');
                    }
                }
            }else{
                var newFiles = [];
                newFiles.push(files[0]);
                files = newFiles;
            }
            for(var i=0;i<files.length;i++){
                if(config.isFujian && i>(GLOBAL.AttachmentNumber - 1)){
                    layer.msg('最多上传'+GLOBAL.AttachmentNumber+'个附件');
                    break;
                }
                if(config.isFujian && th.children().length >= GLOBAL.AttachmentNumber){
                    layer.msg('最多上传'+GLOBAL.AttachmentNumber+'个附件');
                    break;
                }
                (function (i) {
                    //console.log(files[i]);
                    var img_name = files[i].name;
                    var img_type = files[i].type;
                    var img_size = files[i].size;
                    if(config.isFujian){
                        if(img_size < 1024*1024*GLOBAL.AttachmentSize){
                            if(filterFileType(img_name)){
                                var randoms = '';
                                for(var n=0;n<10;n++){
                                    randoms += Math.floor(Math.random()*10);
                                }
                                var fileTypeArr = img_name.split('.');
                                var fileType = fileTypeArr[fileTypeArr.length-1].toLowerCase();
                                th.append('<p class="file-'+randoms+'"><a class="inline fjRow defaultColor cursor" data-type="'+fileType+'" target="_blank"><i class="fa fa-paperclip"></i><span class="fj-name"> '+img_name+'</span></a> <span class="right defaultColor">正在上传 <em class="file-progress">0%</em></span></p>');
                                var formData = new FormData();
                                formData.charset = 'UTF-8';
                                formData.append('token',token);
                                if(config.isMobile){
                                    formData.append('projectId',config.projectId);
                                }else{
                                    formData.append('projectId',_projectId);
                                }
                                formData.append('channel',config.channel);
                                formData.append('file',files[i]);
                                formData.append('attachment',true);
                                ajax(formData, function (percent) {
                                    if(percent == 100){
                                        $('.file-'+randoms+' .right').html('正在处理');
                                    }else{
                                        $('.file-'+randoms+' em').html(percent+'%');
                                    }
                                }, function (rs) {
                                    if(rs.success){
                                        $('.file-'+randoms+' a.fjRow').attr({'data-url':rs.root.url,'href':rs.root.url});
                                        $('.file-'+randoms+' span.right').html('<i class="fa fa-times-circle-o del" id="'+rs.root.id+'" alt="删除" title="删除"></i>');
                                        $('.file-'+randoms+' span.right').prepend('<i class="fa fa-pencil-square-o edit" id="'+rs.root.id+'" data-name="'+rs.root.originalFileName+'" alt="编辑名称" title="编辑名称"></i>');
                                        $('.file-'+randoms+' span.right .edit').click(function () {
                                            var $this = $(this);
                                            $('#myAttachmentsEditDisplayNameForm input[name="id"]').val($this.attr('id'));
                                            $('#myAttachmentsEditDisplayNameForm input[name="originalFileName"]').val($this.attr('data-name'));
                                            $('#myAttachmentsEditDisplayName').modal('show');
                                        });
                                    }else{
                                        $('.file-'+randoms+' em').html('上传失败');
                                        $('.file-'+randoms+' span.right').html('<i class="fa fa-times-circle-o del" alt="删除" title="删除"></i>');
                                    }
                                    $('.file-'+randoms+' span.right .del').click(function () {
                                        $(this).parents('p').remove();
                                    });
                                    
                                });
                            }else{
                                th.append('<p><i class="fa fa-file-o"></i> '+img_name+' <span class="right">上传失败，不允许的文件格式</span></p>');
                            }
                        }else{
                            th.append('<p><i class="fa fa-paperclip"></i> '+img_name+' <span class="right f12 red">上传失败，文件太大（建议'+GLOBAL.AttachmentSize+'M以内） <i class="fa fa-times-circle-o del" alt="删除" title="删除"></i></span></p>');
                            th.find('p .del').click(function () {
                                $(this).parents('p').remove();
                            });
                        }
                    }else{
                        if(img_type == 'image/jpeg' || img_type == 'image/png' || img_type == 'image/bmp' || img_type =='image/gif' || img_type == 'image/jpg'){
                            if(img_size < 1024*1024*6){
                                var random = '';
                                for(var n=0;n<10;n++){
                                    random += Math.floor(Math.random()*10);
                                }
                                var reader = new FileReader();
                                reader.onload = function(evt){
                                    if(i>(GLOBAL.ImageNumber-1)){
                                        layer.msg('最多上传'+GLOBAL.ImageNumber+'张图片');
                                        return false;
                                    }
                                    if(th.children().length >= GLOBAL.ImageNumber){
                                        layer.msg('最多上传'+GLOBAL.ImageNumber+'张图片');
                                        return false;
                                    }
                                    th.removeClass('upload-file-bg');
                                    if(config.getIsOnly()){
                                        th.html("<div class='upload-img' id='img-"+random+"'>" +
                                            "<div class='ui-image'><img src='"+ evt.target.result +"'  /></div>" +
                                            "<div class='ui-progress'></div>" +
                                            "</div> ");
                                    }else{
                                        th.append("<div class='upload-img' id='img-"+random+"'>" +
                                            "<div class='ui-image'><img src='"+ evt.target.result +"'  /></div>" +
                                            "<div class='ui-progress'></div>" +
                                            "</div> ");
                                        if(typeof config.draggable != 'undefined'){
                                            if(config.draggable){
                                                th.gridly();
                                            }
                                        }else{
                                            th.gridly();
                                        }
                                    }

                                    var formData = new FormData();
                                    formData.append('token',token);
                                    if(config.isMobile)
                                        formData.append('projectId',config.projectId);
                                    else
                                        formData.append('projectId',_projectId);
                                    formData.append('channel',config.channel);
                                    formData.append('file',files[i]);
                                    formData.append('id',config.id);
                                    ajax(formData, function (percent) {
                                        if(percent == 100){
                                            $('#img-'+random+' .ui-progress').html('正在处理');
                                        }else{
                                            $('#img-'+random+' .ui-progress').html(percent+'%');
                                        }
                                    }, function (rs) {
                                        console.log('上传结果',rs);
                                        if(rs.success){
                                            $('#img-'+random+' .ui-progress').html('上传完成');
                                            $('#img-'+random+' .ui-image img').attr({'src':rs.root.thumbUrl,'layer-src':rs.root.url,'alt':rs.root.originalFileName,'title':rs.root.originalFileName});
                                            $('#img-'+random+' .ui-progress').remove();
                                            if(config.getIsOnly()){
                                                callback(rs);
                                                return false;
                                            }
                                            th.find('#img-'+random).append("<div class='ui-opts' data-action='del' id='"+rs.root.id+"'><i class='fa fa-times-circle-o' alt='删除' title='删除'></i></div><div class='ui-opts ui-opts-edit' data-action='edit' data-name='"+rs.root.originalFileName+"' id='"+rs.root.id+"'><i class='fa fa-pencil-square-o' alt='编辑名称' title='编辑名称'></i></div>");
                                            config.imageIds.getId().push(rs.root.id);
                                            bindOptions(th,callback);
                                            callback(config.imageIds.getId());
                                        }else{
                                            $('#img-'+random+' .ui-progress').html('上传失败').addClass('ui-fail').removeClass('ui-progress');
                                            th.find('#img-'+random).append("<div class='ui-opts' data-action='del'><i class='fa fa-times-circle-o' alt='删除' title='删除'></i></div>");
                                            bindOptions(th,callback);
                                        }
                                    });
                                    $('#img-'+random+' .upload-img').click(function(e){
                                        return false;
                                    });
                                };
                                reader.readAsDataURL(files[i]);
                            }else{
                                layer.msg('图片太大，不能超过6M');
                            }
                        }else{
                            console.log('无效格式');
                        }
                    }
                })(i)
            }
        }
    }

    function ajax(formData, callback, results) {
        var xhr = new XMLHttpRequest();
        xhr.open(config.method,config.url);
        xhr.onload = function (data) {
            var isComplate = true;
        };
        xhr.upload.onprogress = function (e) {
            if(e.lengthComputable){
                var percent =(e.loaded / e.total *100|0);
                callback(percent);
            }
        };
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    var response = $.parseJSON(xhr.response);
                    results(response);
                    // if(response.success){
                    //     results(response);
                    // }else{
                    //     session.errorType(response);
                    // }
                    console.log(response);
                }
            }
        };

        xhr.send(formData);
    };

    var bindOptions = function (th,callback) {
        $('.upload-img .ui-opts').click(function () {
            var $$this = $(this);
            if($$this.attr('data-action') == 'del'){
                //console.log('删除操作',config.imageIds.getId(),$$this.attr('id'));
                if(typeof $$this.attr('id') != 'undefined'){
                    var id = $$this.attr('id');
                    var newArrayValue = [];
                    for(var j=0;j<config.imageIds.getId().length;j++){
                        if(config.imageIds.getId()[j]!=id) {
                            newArrayValue.push(config.imageIds.getId()[j]);
                        }
                    }
                    if(newArrayValue.length == 0){
                        init(th,JSON.parse(th.attr('data-config')));
                    }
                    config.imageIds.setId(newArrayValue);
                    callback(config.imageIds.getId());
                    //console.log('目前的图片id',config.imageIds.getId());
                    //$$this.parent().remove();
                }else{
                    //$$this.parent().remove();
                }
                $$this.parent().remove();
            }
            if($$this.attr('data-action') == 'edit'){
                $('#myPictureEditDisplayNameForm input[name="id"]').val($$this.attr('id'));
                $('#myPictureEditDisplayNameForm input[name="originalFileName"]').val($$this.attr('data-name'));
                $('#myPictureEditDisplayName').modal('show');
            }
            return false;
        });
    };

    // 过滤文件格式
    var filterFileType = function (str) {
        var noAllow = ['app','bat','cmd','com','cpl','dll','exe','hta','sys','htt','inf','jse','msi','msp','mst','pif','prf','prg','reg','scf','scr','sct','shb','shs','url','vbe','vbs','vsmacros','ws','wsc','wsf','wsh'];
        var arr = str.split('.');
        if(arr.length>1){
            for(var i=0;i<noAllow.length;i++){
                if(noAllow[i] == arr[arr.length-1]){
                    return false;
                }
            }
        }
        return true;
    };


    return {
        config : config,
        bindOptions : bindOptions
    }
});